import { ref, onMounted, onUnmounted } from "vue";
import { debounce } from "@/utils/utils";

export default function useScrollLoad(
  onScrollEnd: () => any,
  gapHeight: number = 0
) {
  const containerRef = ref<HTMLElement | null>(null);

  const handleLoad = debounce(() => {
    if (containerRef.value) {
      const scrollTop = containerRef.value.scrollTop;
      const scrollHeight = containerRef.value.scrollHeight;
      const height = containerRef.value.clientHeight;
      console.log(scrollHeight - (scrollTop + height));
      if (scrollHeight - (scrollTop + height) <= gapHeight) {
        typeof onScrollEnd === "function" && onScrollEnd();
      }
    }
  }, 100);
  onMounted(() => {
    if (containerRef.value) {
      containerRef.value.addEventListener("scroll", handleLoad);
    }
  });

  onUnmounted(() => {
    if (containerRef.value) {
      containerRef.value.removeEventListener("scroll", handleLoad);
    }
  });

  return { containerRef };
}
